import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oral_cloud/config/app_config.dart';
import 'package:oral_cloud/config/constant.dart';
import 'package:oral_cloud/config/resource_mananger.dart';
import 'package:oral_cloud/config/router_manger.dart';
import 'package:oral_cloud/generated/l10n.dart';
import 'package:oral_cloud/model/patient.dart';
import 'package:oral_cloud/provider/provider_widget.dart';
import 'package:oral_cloud/provider/view_state_widget.dart';
import 'package:oral_cloud/ui/widget/global_widget.dart';
import 'package:oral_cloud/ui/widget/loading_widget.dart';
import 'package:oral_cloud/ui/widget/patient_grid_item.dart';
import 'package:oral_cloud/ui/widget/patient_list_item.dart';
import 'package:oral_cloud/view_model/patient_model.dart';
import 'package:oral_cloud/view_model/user_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class PatientListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _PatientListPageState();
  }
}

class _PatientListPageState extends State<PatientListPage>
    with AutomaticKeepAliveClientMixin {
  String token = UserModel().user.token;

  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidget<PatientModel>(
        model: PatientModel(token),
        onModelReady: (model) {
          model.initData();
        },
        builder: (context, model, child) {
          return Scaffold(
            appBar: GlobalAppBar(
              S.of(context)
                  .patientList,
              widget: GestureDetector(
                  onTap: () =>
                      Navigator.of(context).pushNamed(RouteName.person),
                  child: Image.asset(
                    ImageHelper.wrapAssets('person_center.png'),
                    width: ScreenUtil.getInstance().setHeight(55),
                    height: ScreenUtil.getInstance().setHeight(56),
                  )),
            ).appBar,
            body: SafeArea(
              child: _patientListWidget(context, model),
            ),
          );
        });
  }

  Widget _patientListWidget(BuildContext context, PatientModel model) {
    if (model.isBusy) {
      return LoadingWidget();
    } else if (model.isError ) {
      return ViewStateErrorWidget(
        error: model.viewStateError,
        onPressed: model.initData,
      );
    } else if (model.isEmpty) {
      return MyViewStateEmptyWidget(onPressed: model.initData);
    }
    return AppConfig.isPad
        ? Container(
      width: double.infinity,
      height: double.infinity,
      alignment: Alignment.center,
      color: Color(MYColors.commonBgColor),
      padding: EdgeInsets.symmetric(
        horizontal: ScreenUtil.getInstance().setWidth(104),
        vertical: ScreenUtil.getInstance().setHeight(60),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: GridView.builder(
                physics: ClampingScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  childAspectRatio: 1.5,
                  mainAxisSpacing: ScreenUtil.getInstance().setHeight(40),
                  crossAxisSpacing: ScreenUtil.getInstance().setWidth(40),
                ),
                itemCount: model.list.length,
                itemBuilder: (context, index) {
                  Patient patient = model.list[index];
                  return PatientGridItemWidget(patient, index: index);
                }),
          ),
          TurnPageWidget(curPage:model.currentPageNum,maxPage:model.maxPageNum,onTurnPage: (page){
            model.loadPage(page: page);
          },),
        ],
      ),
    )
        : SmartRefresher(
      controller: model.refreshController,
      header: WaterDropHeader(
        refresh: defaultTargetPlatform == TargetPlatform.iOS
            ? const CupertinoActivityIndicator()
            : const CircularProgressIndicator(
          strokeWidth: 2.0,
          backgroundColor: Color(MYColors.borderFocusColor),
        ),
      ),
      footer: ClassicFooter(
        loadingIcon: defaultTargetPlatform == TargetPlatform.iOS
            ? const CupertinoActivityIndicator()
            : const CircularProgressIndicator(
          strokeWidth: 2.0,
          backgroundColor: Color(MYColors.borderFocusColor),
        ),
      ),
      onRefresh: model.refresh,
      onLoading: model.loadMore,
      enablePullUp: true,
      child: AppConfig.isPad
          ? Container(
        color: Color(MYColors.commonBgColor),
        padding: EdgeInsets.symmetric(
          horizontal: ScreenUtil.getInstance().setWidth(104),
          vertical: ScreenUtil.getInstance().setHeight(60),
        ),
        child: GridView.builder(
            physics: ClampingScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              childAspectRatio: 1.5,
              mainAxisSpacing:
              ScreenUtil.getInstance().setHeight(40),
              crossAxisSpacing:
              ScreenUtil.getInstance().setWidth(40),
            ),
            itemCount: model.list.length,
            itemBuilder: (context, index) {
              Patient patient = model.list[index];
              return PatientGridItemWidget(patient, index: index);
            }),
      )
          : ListView.builder(
          itemCount: model.list.length,
          itemBuilder: (context, index) {
            Patient patient = model.list[index];
            return PatientItemWidget(patient, index: index);
          }),
    );
  }



}


// ignore: must_be_immutable
class TurnPageWidget extends StatefulWidget{
  final TurnPageCallback onTurnPage;
  int curPage;
  int maxPage;

  TurnPageWidget({this.curPage,this.maxPage, this.onTurnPage});
  @override
  State<StatefulWidget> createState() {
    return _TurnPageWidgetState();
  }


}

typedef TurnPageCallback = void Function(int page);

class _TurnPageWidgetState extends State<TurnPageWidget>{



  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        GestureDetector(
          onTap: widget.curPage==1?null:(){
            widget.onTurnPage(--widget.curPage);
            },
          child: Text('上一页',style: TextStyle(color: Color(widget.curPage==1?MYColors.textNormalColor:MYColors.textHighlightColor)),),
        ),
        SizedBox(width: 20,),
        Text('${widget.curPage}/${widget.maxPage}',style: TextStyle(color: Color(MYColors.textNormalColor)),),
        SizedBox(width: 20,),
        GestureDetector(
          onTap: widget.curPage==widget.maxPage?null:(){
            widget.onTurnPage(++widget.curPage);
          },
          child: Text('下一页',style: TextStyle(color: Color(widget.curPage==widget.maxPage?MYColors.textNormalColor:MYColors.textHighlightColor)),),
        ),
      ],
    );
  }

}
